package org.edu.eece262.taskshare;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ReassignTask extends Activity {

	public static final String PREFS_NAME = "TASKSHARELOGIN";

	ScrollView assigned;
	LinearLayout llContacts;
	LinearLayout llGroups;
	TaskDBAdapter taskDBA;
	ContactsDBAdapter contactsDBA;
	GroupDBAdapter groupDBA;
	Button bAssignTask;
	Button bCancelAssign;
	Gson gson;

	LinkedList<String> newAssignees;
	LinkedList<String> newGroups;

	Intent results;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reassigntask);

		taskDBA = TaskDBAdapter.getTSDBAdapter(getApplicationContext());
		contactsDBA = ContactsDBAdapter
				.getContactsDBAdapter(getApplicationContext());
		groupDBA = GroupDBAdapter.getGroupDBA(getApplicationContext());

		bAssignTask = (Button) findViewById(R.id.bAssignTask);
		bCancelAssign = (Button) findViewById(R.id.bCancelReassign);
		llContacts = (LinearLayout) findViewById(R.id.lvContacts);
		llGroups = (LinearLayout) findViewById(R.id.lvGroups);

		newAssignees = new LinkedList<String>();
		newGroups = new LinkedList<String>();

		results = new Intent();

		final int localID = getIntent().getIntExtra("local_id", 0);

		if (localID == 0) {
			results.putExtra("NULL", true);
			setResult(RESULT_CANCELED, results);
			finish();
		}

		Cursor assigned = taskDBA.getTaskWithLocalID(localID);

		gson = new Gson();

		assigned.moveToFirst();

		Type collectionType = new TypeToken<LinkedList<String>>() {
		}.getType();
		LinkedList<String> assignees = gson.fromJson(assigned
				.getString(TaskDBAdapter.ASSIGNED_LIST_COLUMN), collectionType);

		contactsDBA.open();
		Cursor contacts = contactsDBA.getContacts();
		contacts.moveToFirst();

		for (int j = 0; !contacts.isAfterLast(); contacts.moveToNext(), ++j) {
			CheckBox current = new CheckBox(this);
			current.setText(contacts
					.getString(ContactsDBAdapter.USER_NAME_COLUMN));

			boolean notFound = true;
			for (int i = 0; i < assignees.size(); i++) {

				if (assignees.get(i).equalsIgnoreCase(
						contacts.getString(ContactsDBAdapter.USER_NAME_COLUMN))) {
					current.setChecked(true);
					newAssignees.add(contacts
							.getString(ContactsDBAdapter.USER_NAME_COLUMN));
					notFound = false;
				}
			}
			if (notFound) {
				current.setChecked(false);
			}

			current.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					if (isChecked)
						newAssignees.add(buttonView.getText().toString());
					else
						newAssignees.remove(buttonView.getText().toString());
				}
			});

			llContacts.addView(current, j, new ViewGroup.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT));
		}

		groupDBA.open();
		Cursor groups = groupDBA.getAllEntries();
		if (groups != null) {
			SharedPreferences settings = getApplicationContext()
					.getSharedPreferences(PREFS_NAME, 0);
			String user = settings.getString("user", "");
			ArrayList<String> aGroups = new ArrayList<String>();
			for (groups.moveToFirst(); !groups.isAfterLast(); groups
					.moveToNext()) {
				LinkedList<Messages.GroupMember> members = GroupDBAdapter
						.groupMembersFromCursor(groups);
				for (int i = 0; i < members.size(); i++) {
					if (members.get(i).getGroupMemberUser().equals(user)
							&& members.get(i).getGroupMemberStatus() == Messages.GroupMember.StatusType.ACTIVE) {
						aGroups.add(groups
								.getString(GroupDBAdapter.NAME_COLUMN));
					}
				}
			}

			for (int k = 0; k < aGroups.size(); ++k) {
				CheckBox current = new CheckBox(this);
				current.setText(aGroups.get(k));

				boolean notFound = true;
				for (int i = 0; i < assignees.size(); i++) {

					if (assignees.get(i).equalsIgnoreCase(aGroups.get(k))) {
						current.setChecked(true);
						newGroups.add(aGroups.get(k));
						notFound = false;
					}
				}
				if (notFound) {
					current.setChecked(false);
				}

				current
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {
							@Override
							public void onCheckedChanged(
									CompoundButton buttonView, boolean isChecked) {
								if (isChecked)
									newGroups.add(buttonView.getText()
											.toString());
								else
									newGroups.remove(buttonView.getText()
											.toString());
							}
						});

				llGroups.addView(current, k, new ViewGroup.LayoutParams(
						ViewGroup.LayoutParams.FILL_PARENT,
						ViewGroup.LayoutParams.WRAP_CONTENT));
			}
		}

		bAssignTask.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				HTTPHelp.getActivityHTTPHelp().assignTask(localID,
						newAssignees, getApplicationContext());
				for (int i = 0; i < newGroups.size(); ++i) {
					HTTPHelp.getActivityHTTPHelp().assignToGroupOneShot(
							localID, newGroups.get(i), getApplicationContext());
				}
				finish();
			}
		});

		bCancelAssign.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

}
